﻿using System.Windows;
using System.Collections.ObjectModel;
using D.WPF.MVVM;
using D.WPF.MVVM.EventUtil;
using System.Windows.Controls;
using CarAppClient.Views.LeftMenu.Models;
using CarAppClient.Controls.TransitionsUserControls;
using CarAppClient.Views.LeftMenu.Views;
using HandyControl.Controls;
using HandyControl.Properties.Langs;
using HandyControl.Tools;
using System.Xml.Linq;
using TabItem = System.Windows.Controls.TabItem;
using System.Windows.Threading;


namespace CarAppClient.Views.LeftMenu.ViewModels
{
    public class LeftMenuListVM : BaseMvvm
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="home"></param>
        public LeftMenuListVM()
        {
            MenuModuleList = new ObservableCollection<SystemModule>();
            LoadData();
        }

        #region 页面属性

        /// <summary>
        /// 菜单模块列表
        /// </summary>
        public ObservableCollection<SystemModule>? MenuModuleList { get; set; }

        public SystemModule? CurrentOpenSystemModule { get; set; }
        //public MenuItemModel? CurrentOpenMenuItem { get; private set; }

        #endregion

        #region 顶部菜单标题连接

        public D.WPF.MVVM.EventUtil.DelegateCommand TopTitleLinkCommand => new(TopTitleLink);
        private void TopTitleLink(object? obj)
        {

        }
        #endregion

        #region 切换菜单

        public DelegateCommandT<SelectionChangedEventArgs>? SwitchMenuCommad => new(SwitchMenu);
        private void SwitchMenu(SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0) return;
            if (e.AddedItems[0] is Models.MenuItemModel item)
            {
                //if (Equals(CurrentOpenMenuItem, item)) return;
                //CurrentOpenMenuItem = item;

                // 触发事件
                var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();

                if (mainWindow != null)
                {
                    var tabContorl = CarAppClient.Helpers.VisualHelper.FindVisualElement<System.Windows.Controls.TabControl>(mainWindow, "tabContorl");

                    //Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    //{
                    if (tabContorl != null)
                    {
                        try
                        {
                            foreach (UIElement tablControl in tabContorl.Items)
                            {
                                TabItem tabtemp = (TabItem)tablControl;
                                if (tabtemp.Header.ToString() == item.Name)
                                {
                                    tablControl.Visibility = Visibility.Visible;
                                    tablControl.Focus();
                                    return;
                                }
                            }
                            TabItem newItem = new TabItem() { Header = item.Name, IsSelected = true };
                            Frame frame = new Frame() { Source = new Uri(item.PageKey, UriKind.Relative) };
                            newItem.Content = frame;
                            tabContorl.Items.Add(newItem);
                            tabContorl.SelectedItem = newItem;
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                    }
                }
                //}), DispatcherPriority.ApplicationIdle);

            }
        }
        #endregion

        #region 获取菜单

        private AnimationTypeEnum _animationTypeEnumType = AnimationTypeEnum.Default;
        /// <summary>
        /// 动画类型
        /// </summary>
        public AnimationTypeEnum AnimationTypeEnumType
        {
            get => _animationTypeEnumType;
            set => SetProperty(ref _animationTypeEnumType, value);
        }

        private bool network = false;
        public bool Network
        {
            get => network;
            set => SetProperty(ref network, value);
        }
        public void LoadData()
        {
            Helpers.NetworkHelper.Initialization();
            IsAvailable = Helpers.NetworkHelper.GetLocalNetworkStatus();
            Helpers.NetworkHelper.NetworkAvailabilityChanged += Network_NetworkAvailabilityChanged;
            GetMenuList();
            //if (MenuModuleList != null)
            //{
            //    // 取第一个页面作为显示到第一个
            //    var home = MenuModuleList.First();
            //    if (home.Data != null)
            //    {// 没有子页面，直接作为第一个页面显示到第一个
            //        MenuItemModel = home;
            //        home.IsSelected = true;
            //    }
            //}
        }

        bool IsAvailable = false;
        private void Network_NetworkAvailabilityChanged(bool isAvailable)
        {
            Network = isAvailable;
            if (!IsAvailable && Network == true)
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    GetMenuList();
                    //MenuItemModel = MenuItemList.First().Data.First();
                    //MenuItemList.First().IsSelected = true;
                    //MenuItemModel.IsSelected = true;
                    //ExtMessage.Success("网络已恢复", "RootMessageTooken");
                    //ExtMessage.Success("程序已重新加载", "RootMessageTooken");
                }));
            }
            IsAvailable = Network;
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        private void GetMenuList()
        {
            // 1. VIN码数据（车辆识别代码，每辆车有一组由17位代码组合而成的组合代码形成，这组代码是有大概规则的，有如身份证号码，这组代码30年内在全球的汽车数据里面是惟一性的，通过规则定义能匹配汽车型号数据，并得出改码对应车型的唯一零部件数据）
            var carVinModule = new SystemModule
            {
                Key = "CarVin",
                Title = "汽车VIN",
                Description = "WMIB定义表、WMIC定义表、VDS定义表、VIS定义表功能应该可以合并操作",
                SelectedIndex = -1,
                IsGroupEnabled = false,
                MenuItemList = new List<Models.MenuItemModel>()
                {
                    new Models.MenuItemModel()
                    {
                        Name = "VIN码", IsVisible =true, QueriesText ="VIN",
                        Description ="通过实码或规则查询（实码查询WMI表、VDS表、VIS表对比精准车型表），得出关联结果，核实正确性，形成VIN表，包含WMI码、VDS码、VIS码、精准车型代码、等字段信息",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName = null,
                        PageKey="Views/CarVin/Views/Page_VIN.xaml"
                    },
                },
            };
            MenuModuleList.Add(carVinModule);
            // 2. 功能模块
            var systemModule = new SystemModule
            {
                Key = "Sys",
                Title = "系统管理",
                SelectedIndex =-1,
                IsGroupEnabled = true,
                MenuItemList = new List<Models.MenuItemModel>()
                {
                    //new Models.MenuItemModel()
                    //{
                    //    Name = "Home",
                    //    IsVisible =true,
                    //    QueriesText ="首页",
                    //    PageKey = "Views/Dashboard/Views/Page_Dashboard.xaml",
                    //    TargetCtlName = "BrushDemoCtl",
                    //    ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                    //    IsNew = false,
                    //    GroupName = "系统设置"
                    //},
                    new Models.MenuItemModel()
                    {
                        Name = "用户管理",
                        IsVisible =true,
                        QueriesText ="User",
                        PageKey="Views/Sys/Views/Page_User.xaml",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName = "系统设置"
                    },
                      new Models.MenuItemModel()
                     {
                        Name = "区域", IsVisible =true, QueriesText ="Area",
                        Description ="区域表：包含区域代码、区域名称（中英文）等信息",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName =  "系统设置",
                      PageKey="Views/CarType/Views/Area/Page_Area.xaml"
                    },
                    new Models.MenuItemModel()
                    {
                        Name = "国家", IsVisible =true, QueriesText ="Country", 
                        Description ="以区域表为上级关联表，建立包含区域代码、国家代码、国家名称（中英文）等信息",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName =  "系统设置",
                      PageKey="Views/CarType/Views/Country/Page_Country.xaml"
                    },
                    new Models.MenuItemModel()
                    {
                        Name = "车辆配件类型",
                        IsVisible =true,
                        QueriesText ="CarPartsType",
                        PageKey="Views/CarParts/Views/CarPartsType/Page_CarPartsType.xaml",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName = "备件设置"
                    },
                    new Models.MenuItemModel()
                    {
                        Name = "品牌", IsVisible =true, QueriesText ="Brand",
                        Description ="建立品牌表，包含品牌代码（品牌ID）、品牌名称（中英文）、品牌归宿地、品牌所在地（制造国）等信息【WMI表、车系表、配件属性表、车辆构造表、配件名称表、配置表】",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName =  "汽车设置",
                      PageKey="Views/CarType/Views/Brand/Page_Brand.xaml"
                    },             
                    new Models.MenuItemModel()
                    {
                        Name = "车系", IsVisible =true, QueriesText ="VehicleSeries",
                        Description ="包含品牌代码、车系代码（车系ID）、车系名称（中英文）、车系型号等信息【公告号表、车型表、配件属性表】",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                      GroupName =  "汽车设置",
                      PageKey="Views/CarType/Views/VehicleSeries/Page_VehicleSeries.xaml"
                    },
                    new Models.MenuItemModel()//销售车型,精准车型,普通车型都是车型，以VehicleType区分
                    {
                        Name = "车型", IsVisible =true, QueriesText ="CarType",
                        Description ="包含品牌代码、车系代码、车型代码、车型名称（中英文）、车型型号等信息【车型配置表、包含以下子表：发动机型号表、变速箱型号表】",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName =  "汽车设置",
                      PageKey="Views/CarType/Views/CarType/Page_CarType.xaml"
                    },
                    new Models.MenuItemModel()
                    {
                        Name = "车型版本", IsVisible =true, QueriesText ="CarTypeVersion",
                        Description ="包含品牌代码、车系代码、车型代码、车型版本代码、配置代码等信息【发动机信息表、变速箱信息表】",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                      GroupName =  "汽车设置",
                      PageKey="Views/CarType/Views/CarTypeVersion/Page_CarTypeVersion.xaml"
                    },
                }
            };
            MenuModuleList.Add(systemModule);

         

            //规则

            var ruleModule = new SystemModule
            {
                Key = "Rule",
                Title = "规则功能",
                Description = "匹配规则模块",
                SelectedIndex = -1,
                IsGroupEnabled = false,
                MenuItemList = new List<Models.MenuItemModel>()
                {
                    new Models.MenuItemModel()
                    {
                        Name = "主规则", IsVisible =true, QueriesText ="RuleConfig",
                        Description ="",
                        TargetCtlName = "BrushDemoCtl",
                        ImageBrush = ResourceHelper.GetResource<object>("Brush.Brush"),
                        IsNew = false,
                        GroupName = null,
                      PageKey="/Views/Rule/Views/RuleConfig/Page_RuleConfig.xaml"
                    },
                }
            };
            MenuModuleList.Add(ruleModule);      
        }
        #endregion
    }
}
